package com.joker.demo.admin.controller;

import com.joker.demo.admin.common.Result;
import com.joker.demo.admin.service.ExecutorCleanupService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 执行器清理控制器
 *
 * @author : feixiang.li
 * @since : 2025-01-27 10:00
 */
@RestController
@RequestMapping("/api/executor-cleanup")
@Tag(name = "执行器清理管理", description = "执行器清理相关接口")
@Slf4j
public class ExecutorCleanupController {

    @Resource
    private ExecutorCleanupService executorCleanupService;

    @PostMapping("/clean-offline-executors")
    @Operation(summary = "手动清理离线执行器", description = "手动触发清理离线执行器的任务")
    public Result<String> cleanOfflineExecutors() {
        try {
            log.info("手动触发清理离线执行器任务");
            executorCleanupService.checkAndCleanOfflineExecutors();
            return Result.success("离线执行器清理任务执行完成");
        } catch (Exception e) {
            log.error("手动清理离线执行器失败", e);
            return Result.error("清理失败: " + e.getMessage());
        }
    }

    @PostMapping("/clean-registry")
    @Operation(summary = "清理注册表中的离线执行器", description = "清理t_job_registry表中的离线执行器")
    public Result<String> cleanOfflineExecutorsFromRegistry() {
        try {
            log.info("手动触发清理注册表中的离线执行器");
            executorCleanupService.cleanOfflineExecutorsFromRegistry();
            return Result.success("注册表清理任务执行完成");
        } catch (Exception e) {
            log.error("清理注册表中的离线执行器失败", e);
            return Result.error("清理失败: " + e.getMessage());
        }
    }

    @PostMapping("/update-job-status")
    @Operation(summary = "更新任务状态", description = "更新t_job_info表中的triggerStatus")
    public Result<String> updateJobInfoTriggerStatus() {
        try {
            log.info("手动触发更新任务状态");
            executorCleanupService.updateJobInfoTriggerStatus();
            return Result.success("任务状态更新完成");
        } catch (Exception e) {
            log.error("更新任务状态失败", e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }
}
